/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.generalfile.servlet;

import cn.net.greenet.common.db_service.ConfigManager;
import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.generalfile.logic.DataChange;
import cn.net.greenet.generalfile.logic.GeneralFileProcess;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 读取用户上传的IP 地址库文件入库
 *
 * @author ShiYun,2014/11/04
 */
@WebServlet(name = "GetIpBank2DB", urlPatterns = {"/common/read_ip_bank"})
public class GetIpBank2DB extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String path = request.getParameter("path");
        String MessageType = request.getParameter("MessageType");
        String policy_instance = request.getParameter("policy_instance");

        boolean result = false;
        GeneralFileProcess pro = new GeneralFileProcess(path, MessageType, policy_instance);
        String name = ConfigManager.getInstance().getString("ipBankFileName");
        path = pro.saveFile(request, name);
        if (path != null) {
            List<String> list = pro.getContent(path, 4);
            if (!list.isEmpty()) {
                pro.init();
//                SessionFactory sf = HibernateUtil.getSessionFactory();
//                Session session = sf.openSession();
//                session.clear();
//                Transaction tx = session.beginTransaction();
//                Iprangeinfo ipbank = null;
//                try {
                List<String> insert = new ArrayList<String>();
                Map<String, Integer> map = pro.getareids();
                for (String line : list) {
//                        ipbank = new Iprangeinfo();
                    String[] ss = line.split("\t");
                    String areaName = ss[3].trim();
                    String IPAT = ss[0].trim();
                    int id = DataChange.hex2dec(IPAT);
                    ss[3] = id + "";
//                        ss[0] = areaName;
//                        ipbank.setAreaName(areaName);
                    int areaNameId = map.size() + 1;
                    if (map.containsKey(areaName)) {
                        areaNameId = map.get(areaName);
                    } else {
                        map.put(areaName, areaNameId);
                    }
//                    System.out.println("areaName:"+areaName+", id:"+areaNameId);
//                        ipbank.setStartIp(ss[1]);
//                        ipbank.setEndIp(ss[2]);
//                        if (id == 4) {
//                            ipbank.setType(1);
//                        } else {
//                            ipbank.setType(0);
//                        }
                    int type = 1;
                    if (id != 4) {
                        type = 0;
                    }
//                        session.save(ipbank);
//                    pro.insert(GeneralFileProcess.INSERT_IP_BANK, new Object[]{areaName, ss[1], ss[2], type, areaNameId});
                    String mes = areaName + "," + ss[1] + "," + ss[2] + "," + type + "," + areaNameId;
                    insert.add(mes);
                }
//                    tx.commit();
                try {
                    pro.batch(GeneralFileProcess.INSERT_IP_BANK, insert);
                    result = true;
                } catch (Exception e) {
                    result = false;
                }

//                } catch (Exception e) {
//                    tx.rollback();
//                    result = false;
//                } finally {
//                    session.close();
//                }
                pro.close();
                try {
                    PolicySupport policySupport = PolicySupport.getInstance();
                    String policy = policySupport.getApi().getMessage("0xCA", "默认库", 0).getSvnFile().getContent();
                    String comment = policySupport.getApi().getMessage("0xCA", "默认库", 0).getSvnFile().getComment();
                    policySupport.getApi().updatePolicy("0xCA", "默认库", 0, policy, comment);
                } catch (Exception e) {
                }
            }
        }
        try (PrintWriter out = response.getWriter()) {
            out.println(result);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
